package com.example.wilson.lifediary;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;

public class DiaryEditor extends Activity {

    private static final String TAG = "Diary";
    public static final String EDIT_DIARY_ACTION = "com.example.wilson.lifediary.DiaryEditor.EDIT_DIARY";
    public static final String INSERT_DIARY_ACTION = "com.example.wilson.lifediary.DiaryEditor.action.INSERT_DIARY";
    public static final  int MENU_ITEM_DELETE = Menu.FIRST +1;
    public static final  int MENU_ITEM_ADDPHOTO = Menu.FIRST +2;


    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private NoteDao noteDao;
    private Note note;
    private Cursor cursor;

    private static final int STATE_EDIT = 0;
    private static final int STATE_INSERT = 1;
    private String dUriString;
    private int mState;
    private Uri mUri;
    private Cursor mCursor;
    private EditText mTitleText;
    private EditText mBodyText;
    private TextView addText;
    private Button confirmButton;
    private long mid;
    private  Button shareButton;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    public String address;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(android.R.style.Theme_Black);
        final Intent intent = getIntent();
        final String action = intent.getAction();
        setContentView(R.layout.diary_edit);

        mTitleText = (EditText)findViewById(R.id.title);
        mBodyText = (EditText)findViewById(R.id.body);
        confirmButton = (Button)findViewById(R.id.confirm);
        shareButton = (Button)findViewById(R.id.shareButton);
        addText = (TextView)findViewById(R.id.location_view);

        //Toast.makeText(DiaryEditor.this, "跳转成功", Toast.LENGTH_LONG).show();
        InitDAO();
        Log.d("action", action);

        //编写日记
        if(EDIT_DIARY_ACTION.equals(action)){
            Toast.makeText(DiaryEditor.this, "用户点击列表成功", Toast.LENGTH_LONG).show();
            Bundle bundle = new Bundle();
            bundle = this.getIntent().getExtras();
            mid = bundle.getLong("id");
            Toast.makeText(DiaryEditor.this, mid+"", Toast.LENGTH_LONG).show();
            note = noteDao.loadByRowId(mid);

            mTitleText.setTextKeepState(note.getTitile());
            mBodyText.setTextKeepState(note.getBody());

            setTitle("编辑日记");
        }else if(INSERT_DIARY_ACTION.equals(action)){
            //新建日记
            Toast.makeText(DiaryEditor.this, "用户点击新建日记成功", Toast.LENGTH_LONG).show();
            mState = STATE_INSERT;
            setTitle("新建日记");
        }else {
            Log.e(TAG, "no such action error");
            finish();
            return;
        }

        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mState == STATE_INSERT){
                    insertDiary();
                }else{
                    updateDiary();
                }
                Intent intent = new Intent(DiaryEditor.this, MainActivity.class);
                startActivity(intent);
                DiaryEditor.this.finish();
            }
        });

        shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String shareContent = mBodyText.getText().toString();
                Intent intent=new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, "Share");
                intent.putExtra(Intent.EXTRA_TEXT, shareContent);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(Intent.createChooser(intent, getTitle()));
            }
        });

        startLocate();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                addText.setText(address);
                Log.e("add：", address);
                //addText.setText(address);
            }
        }, 2000);

    }

    @Override
    public void onBackPressed() {
        if(mState == STATE_INSERT){
            insertDiary();
        }else{
            updateDiary();
        }
        Intent intent = new Intent(DiaryEditor.this, MainActivity.class);
        startActivity(intent);
        DiaryEditor.this.finish();
    }

    private void InitDAO(){
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        noteDao = daoSession.getNoteDao();
    }

    private void insertDiary(){
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        String date = df.format(new Date());

        Note note = new Note(null, title, body, date);
        noteDao.insert(note);

        Log.d("DaoExaple" , "inserted new note ID:"+note.getId());

    }
    private void updateDiary(){
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        String date = df.format(new Date());
        noteDao.deleteByKey(mid);
        Note note = new Note(null, title, body, date);
        noteDao.insertOrReplace(note);
    }



    //添加菜单键选项

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
         super.onCreateOptionsMenu(menu);

        menu.add(Menu.NONE,MENU_ITEM_DELETE,0,R.string.menu_delete);
        return true;
    }

    //添加选择菜单的选择事件

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case MENU_ITEM_DELETE:
                noteDao.deleteByKey(mid);
                Toast.makeText(DiaryEditor.this, "删除成功", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(DiaryEditor.this,MainActivity.class);
                startActivity(intent);
                DiaryEditor.this.finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 定位
     */
    private void startLocate() {
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
        //开启定位
        mLocationClient.start();
    }


    private class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                address = location.getAddrStr();
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
           // Log.e("描述：", sb.toString());
            //Log.e("add：", address);
            //addText.setText(address);
            
        }
    }
}
